class AlertService
  def self.check_rule(obj, rule)
    puts "obj[rule.metric].nil?" if obj[rule.metric].nil?
    if evaluate_condition(obj[rule.metric].to_f, rule.condition, rule.threshold)
      process_alert(obj, rule)
    end
  end

  def self.evaluate_condition(value, operator, threshold)
    puts value, threshold
    value.send(operator, threshold)
  end

  def self.process_alert(obj, rule)
    msg = "#{rule.category}: #{obj["name"]} #{rule.condition} #{rule.metric} #{rule.threshold} 触发值: #{obj[rule.metric]}"
    latest_alert = AlertRecord
                     .where(name: obj["name"], alert_rule: rule)
                     .order(alert_time: :desc)
                     .first
    return if latest_alert && latest_alert.alert_time > rule.frequency.minutes.ago
    Robot.send_alert msg
    AlertRecord.create!(
      name: obj["name"],
      alert_rule: rule,
      alert_time: Time.current,
      value: obj[rule.metric],
      level: rule.level,
      status: :sent,
      message: msg
    )
  end
end